import {
  SET_TOKEN,
  SET_USERINFO,
  SET_MENULIST,
  SET_ROLELIST,
} from '../action/types'
import { storeData } from '../../util/index'

let cache = sessionStorage.getItem('redux-data') || '{}'

cache = JSON.parse(cache)

const initState = {
  token: cache.token || '',
  userInfo: cache.userInfo || {},
  menuList: cache.menuList || [],
  roleList: cache.roleList || [],
}

export default function (state = initState, action) {
  let newState
  switch (action.type) {
    case SET_TOKEN:
      newState = {
        ...state,
        token: action.token,
      }

      storeData(newState)

      return newState

    case SET_USERINFO:
      newState = {
        ...state,
        userInfo: action.userInfo,
      }
      storeData(newState)
      return newState

    case SET_MENULIST:
      newState = {
        ...state,
        menuList: action.menuList,
      }
      storeData(newState)
      return newState

    case SET_ROLELIST:
      newState = {
        ...state,
        roleList: action.roleList,
      }
      storeData(newState)
      return newState

    default:
      return JSON.parse(JSON.stringify(state))
  }
}

/* 对state里面的数据进行优化处理， 利用自定义的storeData() */
/* 
 function  storeData(data){
  sessionStorage.setItem('redux-data',JSON.stringify(data))
} */
